/*
 * @Description:
 * @Author: Evan.Zhang
 * @Date: 2022-07-08 14:23:57
 * @LastEditTime: 2022-08-05 18:19:15
 * @LastEditors: Evan.Zhang
 * @Reference:
 */
import path from "path"
import fs from "fs"
import { uglify } from "rollup-plugin-uglify";

async function injectStringByFile(options) {
  let filePath = options.args[0]
  filePath = path.join(__dirname, filePath)
  console.log("  注入文件路径为:", filePath);
  let code = ""
  if (/^.*\.js$/gs.test(filePath) && process.env.ENV === 'production') {
    const compiler = uglify();
    console.log("  当前为 '生产模式': 执行注入文件代码混淆");
    let injectContent = fs.readFileSync(filePath, 'UTF-8');
    compiler.renderStart();
    const compilerContent = compiler.renderChunk(injectContent)
    const result = await compilerContent
    console.log("======== SourceMap: =====================================")
    console.log(result.map);
    console.log("=========================================================")
    code = result.code
    compiler.generateBundle();
  } else {
    console.log("  当前为 '开发模式': 注入文件无需混淆");
    code = fs.readFileSync(filePath, 'UTF-8');
  }
  return code;
}

async function injectTextBlobLink(options) {
  const variableName = options.args[0]
  const code = `const ${variableName} = URL.createObjectURL(new Blob([\`${ options.pipeValue }\`], {
    type: 'text/plain'
  }))`
  console.log(`  已注入Blob link代码片段`);
  return code;
}

async function deleteThisLine(options) {
  options.pool.splice(options.poolIdx , 1)
  return options.pipeValue;
}

export default {
  // 注入文件内容到代码
  injectStringByFile,
  // 替换blob对象
  injectTextBlobLink,
  deleteThisLine
}